<template>
  <div>
    <el-form :model="currentRecord" ref="editForm" :rules="recordRules" label-width="120px">
      <el-form-item label="分发内容:" prop="content">
        <el-col :span="18">
          <el-input v-model="currentRecord.content" :disabled="this.mode == 'details'" placeholder="请输入分发内容"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="选择分发人员:" prop="receiverIds">
        <el-col :span="18">
          <el-cascader v-model="currentRecord.receiverIds" style="width: 100%;" :options="options" :props="props"
            :show-all-levels="false">
            <template #default="{ node, data }"> <!-- 注意使用的是 #default -->
              <span>{{ data.name }}{{data.roleName?`&nbsp&nbsp(${data.roleName})`:'' }}</span> <!-- 假设每个选项对象中有一个otherField字段 -->
            </template>
          </el-cascader>
        </el-col>
      </el-form-item>
      <!-- <el-form-item label="分发文件:" prop="files" >
        <el-col :span="18">
          <el-upload ref="upload" class="upload-demo" drag :action="action" multiple :headers="headers"
            :on-success="handleAvatarSuccess" :on-change="handleFileChange" :on-error="handleAvatarError"
            :before-upload="handleBefore">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-col>
      </el-form-item> -->
      <el-form-item align="center">
        <el-col :span="24">
          <el-button type="primary" :loading="editLoading" @click.native.prevent="handleSubmit">
            <i class="fa fa-save"></i> 保存
          </el-button>
        </el-col>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import DistributionApi from '../api/distribution'
import URL from '@/api/api'
import { Message, Loading } from 'element-ui'
export default {
  name: 'DistributionEdit',
  props: {
    mode: {
      type: String
    },
    record: {
      type: Object
    },
    ifOperation: {
      type: Boolean
    }
  },
  data() {
    const validateLogo = (rule, value, callback) => {
      console.log(this.currentRecord.fileId, this.listLength)
      if (!this.currentRecord.fileId && this.listLength === 0) {
        callback(new Error('请上传文件'))
      } else {
        callback()
      }
    }
    return {
      listLength: 0,
      currentRecord: {
        content: undefined,
        receiverIds: undefined,
        fileId: undefined
      },
      formRules: {},
      editLoading: false,
      options: [{
        value: '选项1',
        label: '黄金糕'
      }, {
        value: '选项2',
        label: '双皮奶'
      }, {
        value: '选项3',
        label: '蚵仔煎'
      }, {
        value: '选项4',
        label: '龙须面'
      }, {
        value: '选项5',
        label: '北京烤鸭'
      }],
      action: URL + "/file/upload",
      headers: {
        Authorization: getToken(),
      },
      props: { multiple: true, value: 'id', label: 'name' },
      options: [],
      loading: null,
      recordRules: {
        content: [{ required: true, trigger: 'blur', message: '请输入分发内容' }],
        receiverIds: [{ required: true, trigger: 'blur', message: '请输入分发人员' }],
        //files: [{ required: true, validator: validateLogo, trigger: 'change' }],
      },
    }
  },
  watch: {
    mode: {
      handler: function (oldValue, newValue) {
        if (this.mode == 'edit' || this.mode == 'distribution') {
          DistributionApi.getSelUpdateDto({ distributionId: this.record.id }).then(resData => {
            if (resData.data.code == 200) {
              this.currentRecord.content = resData.data.data.content
              this.currentRecord.fileId = resData.data.data.fileId
              let receiverIds = resData.data.data.receivers.map(item => [item.deptId, item.receiverId])
              this.currentRecord.receiverIds = receiverIds
            }
          })
        }
      },
      deep: true,
      immediate: true

    }
  },
  mounted() {
    // DistributionApi.getSubDepartmentsWithUsers({ deptId: this.$store.getters.deptId }).then(res => {
    //   this.options = res.data.data
    // })
    DistributionApi.getPeerAndSubDeptsWithUsers().then(res => {
      this.options = [...res.data.data.peerDepartments, ...res.data.data.subDepartments]
    })
  },
  methods: {
    handleSubmit() {
      this.$refs['editForm'].validate(valid => {
        if (valid) {
          let receiverIds = this.currentRecord.receiverIds.map(item => item[1])
          if (this.mode == 'add' || this.mode == 'distribution') {
            if (!this.ifOperation) {
              this.currentRecord.mainRecordId = this.record.id
            }
            let newRecord = Object.assign({}, this.currentRecord)
            this.editLoading = true
            DistributionApi.add({ ...newRecord, receiverIds }).then(rspData => {
              if (rspData.data.code === 200) {
                Message.success('新增成功')
              } else {
                Message.error(rspData.data.message)
              }
              this.editLoading = false
              this.$emit('after-edit')
            })
          } else if (this.mode == 'edit') {
            this.currentRecord.distributionId = this.record.id
            let newRecord = Object.assign({}, this.currentRecord)

            DistributionApi.updateDistribution(newRecord).then(rspData => {
              if (rspData.data.code === 200) {
                Message.success('修改成功')
              } else {
                Message.error(rspData.data.message)
              }
              this.editLoading = false
              this.$emit('after-edit')
            })
          }
        } else {
          return false
        }
      })
    },
    resetFields() {
      this.$refs['editForm'].resetFields()
    },
    handleBefore() {

      this.loading = Loading.service({
        lock: true,
        text: '文件上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.8)'
      })
    },

    handleAvatarSuccess(resp) {
      if (resp.code === 200) {
        this.currentRecord.fileId = resp.data.fileId

        Message.success("上传成功")
      } else {
        Message.error("模板上传失败，格式错误")
      }

      this.loading.close()
    },
    handleAvatarError(error) {
      this.loading.close()
      Message.error("模板上传失败，格式错误!")
    },
    handleFileChange(file, fileList) {  //图片上传后
      this.listLength = fileList.length
      if (this.listLength > 0) {
        this.$refs['editForm'].clearValidate(["files"]);
      }
    }
  }
}
</script>
<style>
.el-cascader-panel {
  height: 400px !important;
  overflow-y: auto !important;
}
</style>